package com.example.auth.controller;

import com.example.auth.common.Result;
import com.example.auth.dto.UserLoginDto;
import com.example.auth.dto.UserRegisterDto;
import com.example.auth.service.AuthService;
import com.example.auth.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 认证控制器
 * 
 * @author Qoder
 * @since 2025-09-06
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody @Validated UserRegisterDto registerDto) {
        try {
            String result = authService.register(registerDto);
            return Result.success("注册成功", result);
        } catch (Exception e) {
            log.error("用户注册失败：{}", e.getMessage());
            return Result.badRequest(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserInfoVo> login(@RequestBody @Validated UserLoginDto loginDto) {
        try {
            UserInfoVo userInfo = authService.login(loginDto);
            return Result.success("登录成功", userInfo);
        } catch (Exception e) {
            log.error("用户登录失败：{}", e.getMessage());
            return Result.unauthorized(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        try {
            authService.logout();
            return Result.success("登出成功");
        } catch (Exception e) {
            log.error("用户登出失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/userinfo")
    public Result<UserInfoVo> getCurrentUser() {
        try {
            UserInfoVo userInfo = authService.getCurrentUser();
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败：{}", e.getMessage());
            return Result.unauthorized(e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("认证系统运行正常");
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result<String> refreshToken() {
        try {
            String token = authService.refreshToken();
            return Result.success("刷新成功", token);
        } catch (Exception e) {
            log.error("刷新token失败：{}", e.getMessage());
            return Result.unauthorized(e.getMessage());
        }
    }
}